import type {Effect, Reducer} from 'umi';
import {currentUser} from '@/services/system/user';
import stringUtil from '@/utils/stringUtil';

export type CurrentUser = {
  userId?: number; // 用户主键 userid
  username?: string; // 用户名
  name?: string; // 名称
  nickName?: string; // 昵称
  sex?: number; // 性别
  birth?: string; // 出身日期
  phone?: string; // 手机号码
  email?: string; // 邮箱
  country?: number; // 国家
  province?: number; // 省
  city?: number; // 市
  county?: number; // 县
  address?: string; // 地址
  headHeadPath?: string; // 头像地址  avatar  // avatar?: string;
  introduction?: string; // 个人简介  profile
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  unreadCount?: number;

};

export type UserModelState = {
  currentUser?: CurrentUser;
};

export type UserModelType = {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
  };
};

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    * fetchCurrent(_, {call, put}) {
      const response = yield call(currentUser);
      if (stringUtil.isEmpty(response.data.headHeadPath)) {
        response.data.headHeadPath = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
      }
      response.data.notifyCount = 12
      response.data.unreadCount = 11;
      yield put({
        type: 'saveCurrentUser',
        payload: response.data,
      });
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default UserModel;
